package org.yty.travelagencymongodb.service.impl;

import cn.hutool.core.util.IdUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;
import org.yty.travelagencymongodb.model.Entity.Route;
import org.yty.travelagencymongodb.repository.RouteRepository;
import org.yty.travelagencymongodb.service.RouteService;

import java.time.LocalDateTime;
import java.util.Optional;

@Service
@RequiredArgsConstructor
public class RouteServiceImpl implements RouteService {
    private final RouteRepository routeRepository;
    private final MongoTemplate mongoTemplate;

    @Override
    public Route getById(Long id) {
        Optional<Route> option = this.routeRepository.findById(id);
        return option.isEmpty() ? null : option.get();
    }

    @Override
    public boolean save(Route route) {
        if (route.getId() == null){
            route.setId(IdUtil.getSnowflakeNextId());
        }
        route.setCreateTime(LocalDateTime.now());
        route.setUpdateTime(LocalDateTime.now());
        route = this.routeRepository.insert(route);
        return route != null;
    }

    @Override
    public boolean update(Route route) {
        route.setUpdateTime(LocalDateTime.now());
        route = this.routeRepository.save(route);
        return route != null;
    }

    @Override
    public void removeById(Long id) {
        this.routeRepository.deleteById(id);
    }
}
